<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class BackStageRobotWorkSum extends Backend
{

    /**
     * LiveStreamer模型对象
     * @var \app\admin\model\LiveStreamer
     */
    protected $model = null;

    protected $admin = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\BackStageRobotWorkSum;

        $this->admin = new Admin();
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {

            $admin = $this->admin->where([
                'status' => 'normal'
            ])->select();

            $list = [];
            foreach ($admin as $item => $value) {
                $list[$value->username] = $value->username;
            }

            $this->assignconfig("adminUserList", $list);
            $this->assign("loginUsername", $this->auth->username);
            $this->assign("loginUserId", $this->auth->username);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $list = $this->model
            ->where($where)
            ->order($sort, $order)
//            ->join("agentstaff_user_list", "agentstaff_user_list.agentID=backstagerobot_work_sum.agentID", "left")
//            ->join("backstagerobot_list", "backstagerobot_list.agentid=backstagerobot_work_sum.agentId")
//            ->field("backstagerobot_work_sum.*,
//            agentstaff_user_list.agentName,
//            agentstaff_user_list.agentID as aagentId,
//            backstagerobot_list.state,
//            backstagerobot_list.lastworktime,
//            backstagerobot_list.ipaddr
//            ")
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function getList()
    {
        $admin = $this->admin->where([
            'status' => 'normal'
        ])->select();

        $list = [];
        foreach ($admin as $item => $value) {
            $list[$value->id] = $value->username;
        }
        return json($list);
    }

    public function getLoginUserId()
    {
        return json($this->auth->id);
    }

    public function checkrobot($ids)
    {
        if (false === $this->request->isPost()) {
            $data = Db::table("admin")->where([
                'username' => request()->get("agentId", null)
            ])->find();

            $this->assign("agentId", request()->get("agentId", null));
            $this->assign("username", $ids);
            $this->assign('data', $data);
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            $param = "'" . $params['username'] . "'," . $params['checkInterval'] . "," . $params['checkmaxtask'] . ",@_res";
            Db::query("call backstagerobot_param_set($param)");
            $result = true;
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
}
